package com.pyb.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileDownloadController {

    private static final String UPLOAD_DIR = "C:\\Users\\pyb\\Desktop\\头像\\springmvc\\target\\springmvc-1.0-SNAPSHOT\\uploads";
    private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class);

    /**
     * 处理文件下载请求。
     *
     * @param filename 请求参数中的文件名
     * @return 返回文件的 ResponseEntity 或者错误状态码
     */
    @GetMapping("/downloadFile")
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam("filename") String filename) {
        logger.info("Attempting to download file: {}", filename);

        // 构建文件路径
        Path path = Paths.get(UPLOAD_DIR, filename);
        logger.info("Constructed file path: {}", path.toString());

        File file = path.toFile();

        // 检查文件是否存在且是普通文件（不是目录）
        if (!file.exists() || !file.isFile()) {
            logger.warn("File does not exist or is not a regular file: {}", filename);
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamResource resource = new InputStreamResource(fileInputStream);

            // 设置响应头信息
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 通用二进制流类型

            // 创建并返回 ResponseEntity
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(file.length())
                    .body(resource);
        } catch (FileNotFoundException e) {
            logger.error("File not found during reading: {}", filename, e);
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}